package com.zygh.coordinatestore.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.zygh.coordinatestore.bean.CorrdinateUtils;
import com.zygh.coordinatestore.entity.Coordinate;
import com.zygh.coordinatestore.mapper.CoordinateMapper;
import com.zygh.coordinatestore.service.CoordinateService;
import com.zygh.coordinatestore.util.Cut;
import com.zygh.coordinatestore.util.WktUtils;
import org.postgis.Polygon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CoordinateServiceImpl implements CoordinateService {
    @Autowired
    private CoordinateMapper coordinateMapper;

    @Override
    public Integer insertSelective(Coordinate coordinate) throws Exception {
        coordinate.setId(IdUtil.simpleUUID());
        coordinate.setCreattime(DateUtil.now());
        Polygon polygon = CorrdinateUtils.formatPolygon(coordinate.getLonLats());   //String类型转换成Polygon类型
        coordinate.setGps(polygon);
        Integer integer = coordinateMapper.insertSelective(coordinate);
        return integer;
    }

    @Override
    public List<Coordinate> findInfoByPolice(String police) throws Exception {
        List<Coordinate> infoByPolice = coordinateMapper.findInfoByPolice(police);
        for (int i = 0; i < infoByPolice.size(); i++) {
            String gps = infoByPolice.get(i).getLonLats();
            String s = WktUtils.wktToJson(gps);
            infoByPolice.get(i).setLonLats(s);
        }

        if (infoByPolice != null) {
            return infoByPolice;
        }
        return null;
    }

    @Override
    public Integer updateByPrimaryKeySelective(Coordinate coordinate) throws Exception {
        //获取修改id查询该条记录的gps
        System.out.println("id：" + coordinate.getId());
        Coordinate infoById = coordinateMapper.findInfoById(coordinate.getId());
        String gps = infoById.getLonLats();
        String s = Cut.cutOut(String.valueOf(gps));  //剪切
        String replace = s.replace(",", ";");
        String replace1 = replace.replace(" ", ",");
        s = replace1 + ";" + coordinate.getLonLats();
        coordinate.setLonLats(s);
        Polygon polygon = CorrdinateUtils.formatPolygon(coordinate.getLonLats());   //String类型转换成Polygon类型
        coordinate.setGps(polygon);
        return coordinateMapper.updateByPrimaryKeySelective(coordinate);

    }
}
